package com.homestead.client;

/**
 * @author HanBin_Yang
 * @since 2021/3/20 15:58
 */
public class AlgorithmUtil {
    private AlgorithmUtil() {}

    /**
     * 选择排序
     * @param arr 泛型数组
     * @param <E>
     */
    public static <E extends Comparable<E>> void selectionSort(E[] arr) {
        for (int i = 0; i < arr.length; i++) {
            int minIndex = i;
            for (int j = i+1; j < arr.length; j++) {
                if (arr[j].compareTo(arr[minIndex]) < 0) {
                    // 数组交换
                    minIndex = j;
                }
            }
            // 交换
            swap(arr, i, minIndex);
        }
    }

    /**
     * 插入排序
     * @param arr
     * @param <E>
     */
    @Deprecated
    public static <E extends Comparable<E>> void insertionSort2(E[] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = i; j - 1 >= 0; j--) {
                if (arr[j].compareTo(arr[j - 1]) < 0) {
                    swap(arr, j, j - 1);
                } else {
                    break;
                }
            }
        }
    }
    public static <E extends Comparable<E>> void insertionSort(E[] arr) {
        for (int i = 0; i < arr.length; i++) {
            E temp = arr[i];
            int j;
            for (j =i; j - 1 >= 0 && arr[j].compareTo(arr[j-1]) > 0; j--) {
                arr[j] = arr[j - 1];
            }
            arr[j] = temp;
        }
    }

    private static <E> void swap(E[] arr, int i, int j) {
        E temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
